// 密码加密
var md5Pwd = require('../utils');
// 数据模型
var model = require('../../model/model');
// 用户信息数据
var User = model.getModel('user');
// 过滤密码和_v
var _filter = {user_pwd: 0, _v: 0};


var userApi = {
	// 注册
	register: function(req, res) {
		var {username, password, email} = req.body;
		// 查询邮箱是否注册过
		User.findOne({user_email: email}, function(err, doc) {
			if (doc) {
				return res.json({code: 1, msg: '该邮箱已注册'});
			}
			// 没有注册就创建数据
			var userModels = new User({user_email: email, user_pwd: md5Pwd(password), user_name: username});
			userModels.save(function(err, doc) {
				if (err) {
					return res.json({code: 1, msg: '服务器崩溃了~~'});
				}
				var {user_email, user_name, _id} = doc;
				// 写入session
				req.session.userinfo = doc;
				return res.json({code: 0, data: {user_email, user_name, _id}});
			});
		});
	},
	// 登录
	login: function(req, res) {
		var { email, password } = req.body;
		// 查询
		User.findOne({user_email: email, user_pwd: md5Pwd(password)}, _filter, function(err, doc) {
			if (!doc) {
				return res.json({code: 1, msg: '邮箱或密码错误'});
			}
			// 写入session
			req.session.userinfo = doc;
			res.json({code: 0, data: doc});
		});
	},
	// 获取用户信息 登陆状态
	getUserinfo: function(req, res) {
		var userinfo = req.session.userinfo;
		if (userinfo) {
			return res.json({code: 0, data: userinfo});
		}
		return res.json({code: 1});
	},
	// 退出
	logout: function(req, res) {
		delete req.session.userinfo;
		return res.json({code: 1, msg: '退出成功'});
	},

}


module.exports = userApi;
